package com.itheima.reggie.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itheima.reggie.common.R;
import com.itheima.reggie.dto.DishDto;
import com.itheima.reggie.entity.Category;
import com.itheima.reggie.entity.Dish;
import com.itheima.reggie.entity.DishFlavor;
import com.itheima.reggie.entity.Setmeal;
import com.itheima.reggie.service.CategoryService;
import com.itheima.reggie.service.DishFlavorService;
import com.itheima.reggie.service.DishService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/dish")
@Slf4j
//菜品管理
public class DishController {
    //引入菜品管理业务层
    @Autowired
    private DishService dishService;
    //引入菜品口味业务层
    @Autowired
    private DishFlavorService dishFlavorService;
    //引入分类管理业务层
    @Autowired
    private CategoryService categoryService;

    //新增菜品
    @PostMapping
    public R<String> save(@RequestBody DishDto dishDto){
        //打印DishDto对象日志
        log.info(dishDto.toString());
        //自己新建一个方法来执行保存
        dishService.saveWithFlavor(dishDto);
        //新增成功返回成功的提示
        return R.success("新增菜品成功");
    }
    //分页查询菜品
    @GetMapping("/page")
    public R<Page> page(int page,int pageSize,String name){
        //创建分页构造器
        Page<Dish> pageInfo=new Page<>(page,pageSize);
        //创建条件构造器
        LambdaQueryWrapper<Dish> lqw = new LambdaQueryWrapper<>();
        //设置模糊查询的条件
        lqw.like(StringUtils.isNotEmpty(name),Dish::getName,name);
        //设置排序， 先根据sort升序排序，sort相同的情况下，再根据修改时间倒序排序
        lqw.orderByAsc(Dish::getSort).orderByDesc(Dish::getUpdateTime);
        //执行语句
        dishService.page(pageInfo,lqw);
        //最后返回的对象
        Page<DishDto> result=new Page<>(page,pageSize);
        //吧查询出来的dish菜品中的数据拷贝到最后要返回的对象中，除了records
        BeanUtils.copyProperties(pageInfo,result,"records");
        //根据Dish菜品查询出来的数据集合
        List<Dish> records = pageInfo.getRecords();
        //获取数据集合中所有分类的id，放入一个新的集合
        List<Long> categoryIdList = records.stream().map(Dish::getCategoryId).collect(Collectors.toList());
        //根据id集合查询出菜品分类集合
        List<Category> categoryList = categoryService.listByIds(categoryIdList);
        //根据查询出来的菜品分类集合，放入map集合中
        Map<Long, String> collect = categoryList.stream().collect(Collectors.toMap(Category::getId, Category::getName));
        //封装到DishDto集合中
        List<DishDto> resultList=records.stream().map(dish -> {
            //创建一个空的dishDto对象
            DishDto dishDto = new DishDto();
            //拷贝属性
            BeanUtils.copyProperties(dish,dishDto);
            //在map集合中查询分类信息
            String categoryName = collect.get(dish.getCategoryId());
            //设置分类名称
            dishDto.setCategoryName(categoryName);
            return dishDto;
        }).collect(Collectors.toList());
        //吧数据封装到最终返回对象Records中
        result.setRecords(resultList);
        //返回最终对象
        return R.success(result);
    }

    //根据id查询菜品及菜品口味信息
    @GetMapping("/{id}")
    public R<DishDto> get(@PathVariable Long id){
        //根据id查询菜品及菜品口味信息
        DishDto dishDto=dishService.getByIdWithFlavor(id);
        //返回查询出的结果
        return R.success(dishDto);
    }
    //修改菜品
    @PutMapping
    public R<String> update(@RequestBody DishDto dishDto){
        //记录要修改的对象日志
        log.info(dishDto.toString());
        dishService.updateWithFlavor(dishDto);
        return R.success("修改菜品成功");
    }
    //修改状态
    @PostMapping("/status/{zt}")
    public R<String> status(@PathVariable String zt, @RequestParam List<Long> ids) {
        List<Dish> dishes = dishService.listByIds(ids);
        if (zt.equals("1")) {
            for (Dish dishe : dishes) {
                dishe.setStatus(1);
            }
        } else if (zt.equals("0")) {
            for (Dish dishe : dishes) {
                dishe.setStatus(0);
            }
        }else {
            return R.error("url错误");
        }
        dishService.updateBatchById(dishes);
        return R.success("修改状态成功");
    }
    //删除
    @DeleteMapping
    public R<String> delete(@RequestParam List<Long> ids) {
        //打印删除成功日志
        log.info("ids:{}", ids);

        //判断是否为空
        if (ids.isEmpty()) {
            return R.error("没有选择删除的套餐");
        }
        //执行删除方法
        dishService.removeWithDish(ids);

        //删除成功后返回
        return R.success("套餐数据删除成功");
    }

    //添加套餐查询菜品
    @GetMapping("/list")
    public R<List<DishDto>> list(Dish dish){
        //构造条件构造器
        LambdaQueryWrapper<Dish> dlqw = new LambdaQueryWrapper<>();
        //添加菜品查询条件
        dlqw.eq(dish.getCategoryId()!=null,Dish::getCategoryId,dish.getCategoryId());
        //添加菜品模糊查询条件
        dlqw.like(StringUtils.isNotEmpty(dish.getName()),Dish::getName,dish.getName());
        //添加条件，状态
        dlqw.eq(Dish::getStatus,1);
        //添加排序
        dlqw.orderByAsc(Dish::getSort).orderByDesc(Dish::getCreateTime);
        //查询
        List<Dish> list = dishService.list(dlqw);
        if (list.isEmpty()){
            return null;
        }
        //获得当前菜品的id
        List<Long> dishId = list.stream().map(Dish::getId).collect(Collectors.toList());
        //获得所有的口味
        LambdaQueryWrapper<DishFlavor> flqw = new LambdaQueryWrapper<>();
        flqw.in(!dishId.isEmpty(),DishFlavor::getDishId,dishId);
        //所有菜品的口味
        List<DishFlavor> dishFlavorList = dishFlavorService.list(flqw);
        //分组
        Map<Long, List<DishFlavor>> listMap = dishFlavorList.stream().collect(Collectors.groupingBy(DishFlavor::getDishId));
        //放入
        List<DishDto> resultList=list.stream().map(dishItem->{
            DishDto dishDto = new DishDto();
            BeanUtils.copyProperties(dishItem,dishDto);
            dishDto.setFlavors(listMap.get(dishItem.getId()));
            return dishDto;
        }).collect(Collectors.toList());

        return R.success(resultList);
    }
}
